package com.core.gig.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.core.as.ASException;
import com.core.gig.as.ASConfiguracao;
import com.core.gig.as.ASFactory;
import com.core.gig.as.ASSeguranca;
import com.core.gig.dto.UsuarioDTO;
import com.core.gig.util.GIGUtil;
import com.core.security.Credential;

/**
 * @author Lucas Ceni
 *
 */
public class LoginAction
		extends GIGAction
{
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		return inicial(mapping, form, request, response);
	}

	public ActionForward inicial(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		clearForm(form);
		return mapping.findForward(FWD_DEFAULT);
	}
	
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		UsuarioDTO usuario = new UsuarioDTO();
		GIGUtil.copyProperties(usuario, form);
		
		try
		{
			ASSeguranca asSeguranca = ASFactory.getInstance().getASSeguranca();
			
			Credential credencial = asSeguranca.login(usuario);
			setCredential(request, credencial);
			
			ASConfiguracao asConfiguracao = ASFactory.getInstance().getASConfiguracao();
			request.setAttribute("sistemaConfigurado", asConfiguracao.sistemaConfigurado());
		}
		catch (ASException e)
		{
			addMessage(request, e.getMessage(), ICO_ERROR);
			return mapping.findForward(FWD_DEFAULT);
		}
		return mapping.findForward(FWD_ENTRADA);
	}
	
	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		invalidateSession(request);
		return inicial(mapping, form, request, response);
	}
}